// Charge l'ensemble des informations des equipements publiques de Nantes
// Basé sur les données open date de Nantes dans une table fusion table

function requestPublicEquipments() {
  var sql = encodeURIComponent("SELECT IDOBJ, CATEGORIE, NOM_COMPLET, LONG_WGS84, LAT_WGS84 FROM 2452195");
  var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + sql);
  query.send(loadPublicEquipments);
}

function loadPublicEquipments(response) { 
  // Load all equipments public and generate markers
  var rows = response.getDataTable(); 
  for (var i=0; i<rows.getNumberOfRows(); i++) {
    var category = rows.getValue(i,1);
    if (category == 1001 || category == 1002) { // parkings
      createPublicEquipmentsMarker('parkings', rows, i);
    } else if (category == 1003) { // bicloos
      createPublicEquipmentsMarker('bicloos', rows, i);       
    } else if (category == 1004) { // transport
      createPublicEquipmentsMarker('transports', rows, i);
    }
  }
  
  // Update parking dispo
  updateParkingDispo();
}

function createPublicEquipmentsMarker(layerName, rows, index) {
  var layer = layers[layerName];
  var id = rows.getValue(index,0);
  var name = rows.getValue(index,2)
  var lng = rows.getValue(index,3);
  var lat = rows.getValue(index,4);
  var point= new google.maps.LatLng(lat, lng); 
  
  var model = new Object();
  model['name'] = name;
  model['lat'] = lat;
  model['lng'] = lng;
  
  var myMarkerOpts = {
    position: point,
    title : name
  };
  if (layerName == 'parkings') {
    myMarkerOpts["icon"] = "./images/grey_parking.png";
  } else if (layerName == 'bicloos') {
    myMarkerOpts["icon"] = "./images/bicloo.png";
  } else if (layerName == 'transports') {
    
  }
  var marker = new google.maps.Marker(myMarkerOpts);
  var infoWindow = new google.maps.InfoWindow();
  
  infoWindow.setContent(name);
  google.maps.event.addListener(marker, 'click', function() {  
    if (openedInfoWindow != null) { 
      openedInfoWindow.close();
    }
    infoWindow.open(map, marker); 
    openedInfoWindow  = infoWindow;
  });              
  
  var markerDef = new Object();
  markerDef['id'] = id;
  markerDef['marker'] = marker;
  markerDef['infoWindow'] = infoWindow;
  markerDef['model'] = model;
  layer['markers'].push(markerDef);
  
}


// Web service de dispo des parkings de Nantes
// INFOS : http://data.nantes.fr/les-donnees/documentation-de-lapi/getdisponibiliteparkingspublics/

// Grp_disponible : Nombre de places disponibles
// Grp_exploitation : Nombre de places ouvertes au clients horaires
// Grp_horodatage : Timestamp de l'information (30/09/2011 11:20:40)
// Grp_complet : Nombre de places minimum devant déclencher l'affichage 'COMPLET'

// Grp_statut : liste des valeurs possibles du champ "statut"
// 0 - Invalide
// 1 - Groupe parking fermé pour tous clients (FERME)
// 2 - Groupe parking fermé au client et ouvert pour les abonnés (ABONNES)
// 5 - Groupe parking ouvert à tous les clients. 
function updateParkingDispo() {
  var request = $.ajax({
    type: "GET",
    url: "http://data.nantes.fr/api/getDisponibiliteParkingsPublics/1.0/39W9VSNCSASEOGV/?output=json",
    dataType: "json"
  });
  request.done(function(msg) {
   
    var parkingList = msg["opendata"]["answer"]["data"]["Groupes_Parking"]["Groupe_Parking"];
    for (var i=0; i<parkingList.length; i++) {
      for (var j=0; j<layers['parkings']['markers'].length; j++) {
        var idParking = layers['parkings']['markers'][j]['id'];
        var marker = layers['parkings']['markers'][j]['marker'];
        var model = layers['parkings']['markers'][j]['model'];
        if (parseInt(idParking) == parseInt(parkingList[i]["IdObj"])) {
          // Get dispo
          var dispo = parkingList[i]["Grp_disponible"];
          var total = parkingList[i]["Grp_exploitation"];
          var name = "<b>" + model['name'] + "</b><br>" + dispo  + " places sur " + total;
          // update info window
          var infoWindow = layers['parkings']['markers'][j]['infoWindow'];         
          infoWindow.setContent(name);          
          // update marker
          var marker = layers['parkings']['markers'][j]['marker'];
          if (dispo <= 1) {
               marker.setIcon('./images/red_parking.png');
          } else if (dispo <= 20) {
               marker.setIcon('./images/orange_parking.png');
          } else {
               marker.setIcon('./images/green_parking.png');
          }
          break; 
        }
      }
    }
  });
  request.fail(function(jqXHR, textStatus) {
    alert("Request failed, Unable to get parking dispo due to : " + textStatus );
  }); 
}



